package xyz.bali16.application.security.advice;

/**
 * @author bali2 on 27/2/2023.
 * @version 1.0
 */

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import xyz.bali16.application.core.enums.ApiEnum;
import java.util.Map;

import static xyz.bali16.application.core.model.Result.success;
@ControllerAdvice
public class Oauth2ResponseBodyAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        //此处返回true,表示对任何handler的responsebody都调用beforeBodyWrite方法，如果有特殊方法不使用可以考虑使用注解等方式过滤
        return true;
    }

    /**
     * 对Controller的所有返回结果进行处理
     *
     * @param body 是controller方法中返回的值，对其进行修改后再return
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        //System.out.println("请求返回数据类型class=" + body.getClass().getName());
         if (body instanceof OAuth2Authentication) {
            // access_token验证
             return success(ApiEnum.GET_SUCCESS, body);
        } else if (body instanceof DefaultOAuth2AccessToken) {
            // 登录获取access_token、refresh_token以及部分身份信息
            return success(ApiEnum.GET_SUCCESS, body);
        } else if (body instanceof Map) {
            // 部分未捕获异常以及token获取用户信息
            return body;
        } else {
            //其他异常或未发现问题直接返回
            return body;
        }

    }
}

